import { ipcMain } from 'electron'

const AI_ASK = 'ai:ask'

async function askWithDashScope({
  prompt,
  apiKey,
  model
}: {
  prompt: string
  apiKey?: string
  model?: string
}) {
  const key = apiKey || process.env.DASHSCOPE_API_KEY || process.env.DASH_SCOPE_API_KEY
  if (!key) {
    throw new Error('未配置阿里云 DashScope API Key（请设置环境变量 DASHSCOPE_API_KEY）')
  }

  const url = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'
  const mdl = model || process.env.DASHSCOPE_MODEL || 'qwen-plus'

  const body = {
    model: mdl,
    messages: [{ role: 'user', content: prompt }],
    temperature: 0.3
  }

  // 使用 Node 18+/Electron 环境内置 fetch
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${key}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  })

  if (!res.ok) {
    const text = await res.text().catch(() => '')
    throw new Error(`DashScope API 请求失败 (${res.status}): ${text || res.statusText}`)
  }

  const data = (await res.json()) as any
  const content: string | undefined = data?.choices?.[0]?.message?.content
  if (!content) {
    return JSON.stringify(data)
  }
  return content
}

export function registerAiHandlers() {
  ipcMain.handle(
    AI_ASK,
    async (_evt, payload: { prompt: string; apiKey?: string; model?: string } | string) => {
      try {
        const p = typeof payload === 'string' ? { prompt: payload } : payload
        return await askWithDashScope({ prompt: p.prompt, apiKey: p.apiKey, model: p.model })
      } catch (error: any) {
        return `出错：${error?.message || String(error)}`
      }
    }
  )
}
